package org.bee.util;

import org.bee.enums.JobErrorProcessType;
import org.bee.enums.JobStatus;
import org.bee.model.BatchJob;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;

/**
 * 任务调度器工具类
 */
public class ScheduleUtils {
    /** 执行目标key */
    public static final String TASK_PROPERTIES = "TASK_PROPERTIES";
    public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME";

    private static Class<? extends Job> getQuartzJobClass(BatchJob sysJob)
    {
        boolean isConcurrent = sysJob.getConcurrent();
        return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class;
    }
    public static void createScheduleJob(Scheduler scheduler, BatchJob job) throws SchedulerException {
        Class<? extends Job> jobClass = getQuartzJobClass(job);
        // 构建job信息
        String id = job.getId();
        String group = job.getJobGroup();
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(id, group)).build();
        // 表达式调度构建器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCron());
        cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder);

        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(id, group))
                .withSchedule(cronScheduleBuilder).build();

        // 放入参数，运行时的方法可以获取
        jobDetail.getJobDataMap().put(ScheduleUtils.TASK_PROPERTIES, job);

        // 判断是否存在
        if (scheduler.checkExists(getJobKey(id, group))){
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(getJobKey(id, group));
        }

        // 判断任务是否过期
        if (null!=CronUtils.getNextExecution(job.getCron())){
            // 执行调度任务
            scheduler.scheduleJob(jobDetail, trigger);
        }

        // 暂停任务
        if (job.getStatus().equals(Boolean.valueOf(JobStatus.STOP.getCode()))){
            scheduler.pauseJob(getJobKey(id, group));
        }
    }

    /**
     * 构建任务触发对象
     */
    public static TriggerKey getTriggerKey(String jobId, String jobGroup)
    {
        return TriggerKey.triggerKey(ScheduleUtils.TASK_CLASS_NAME + jobId, jobGroup);
    }
    /**
     * 构建任务键对象
     */
    public static JobKey getJobKey(String jobId, String jobGroup)
    {
        return JobKey.jobKey(ScheduleUtils.TASK_CLASS_NAME + jobId, jobGroup);
    }

    /**
     * 设置定时任务策略
     */
    public static CronScheduleBuilder handleCronScheduleMisfirePolicy(BatchJob job, CronScheduleBuilder cb){
        if(job.getErrorStrategy().equals(JobErrorProcessType.MISFIRE_DEFAULT.getCode())){
            return cb;
        }
        if(job.getErrorStrategy().equals(JobErrorProcessType.MISFIRE_FIRE_AND_PROCEED.getCode())){
            return cb.withMisfireHandlingInstructionFireAndProceed();
        }
        if(job.getErrorStrategy().equals(JobErrorProcessType.MISFIRE_DO_NOTHING.getCode())){
            return cb.withMisfireHandlingInstructionDoNothing();
        }
        if(job.getErrorStrategy().equals(JobErrorProcessType.MISFIRE_IGNORE_MISFIRES.getCode())){
            return cb.withMisfireHandlingInstructionIgnoreMisfires();
        }
        return cb;
    }
}
